<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="formRef"
      :model="formData"
      label-width="0"
    >
      <el-row style="margin-bottom: 10px " align="bottom">
        <p style="font-weight: bold">粘贴文本</p>
        <p style="margin-left: 10px; font-size: 12px; text-decoration: underline; cursor: pointer" @click="copyContentMethod">点击复制模板</p>
      </el-row>
      <el-row style=" border: 1px solid #999;" type="flex" class="row-bg" justify="center" align="top">
        <el-col :span="leftSpan" class="no-border">
          <el-input type="textarea" v-model="formData.content" :placeholder="copyContent" :autosize="{ minRows: 12, maxRows: 24}" />
        </el-col>
        <el-col :span="rightSpan">
          <el-table
            border
            :data="formSubResult"
            :stripe="true"
            :show-overflow-tooltip="true"
          >
            <el-table-column label="分析对象" align="left" prop="mobile">
              <template #default="{row}">
                <p>{{row.name + ' ' + row.mobile}}</p>
              </template>
            </el-table-column>
            <el-table-column label="分析结果" align="left" prop="result">
              <template #default="{row}">
                <el-tag type="success" v-if="row.result">一致</el-tag>
                <el-tag type="danger" v-else>不一致</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="margin-top: 10px" type="flex" class="row-bg" justify="center" align="center" >
      <el-button @click="submitForm" :disabled="submitFormDisabled" type="primary">{{zndbApi.name + '（' + zndbApi.price + '元/条）'}}</el-button>
<!--      <el-button>重 置</el-button>-->
    </el-row>
  </ContentWrap>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
<!--      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>-->
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
<!--        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:info-comparison:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:info-comparison:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['business:info-comparison:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column
        type="index"
        width="50"/>
<!--    <el-table-column type="selection" width="55" />-->
<!--      <el-table-column label="主键" align="center" prop="id" />-->
<!--      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="部门ID" align="center" prop="deptId" />-->
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="是否一致" align="center" prop="result">
        <template #default="{row}">
          <el-tag type="success" v-if="row.result">一致</el-tag>
          <el-tag type="danger" v-else>不一致</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="查询时间"
        align="center"
        prop="queryTime"
        :formatter="dateFormatter"
        width="180px"
      />
<!--      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />-->
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
<!--          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['business:info-comparison:update']"
          >
            编辑
          </el-button>-->
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:info-comparison:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
<!--  <InfoComparisonForm ref="formRef" @success="getList" />-->
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InfoComparisonApi, InfoComparison } from '@/api/business/infocomparison'
import InfoComparisonForm from './InfoComparisonForm.vue'
import { ApiTypeInfoApi, ApiTypeInfo } from '@/api/business/apitypeinfo'
import {ContentWrap} from "@/components/ContentWrap";
import {BizConfigApi} from "@/api/business/config";

/** 智能比对 列表 */
defineOptions({ name: 'InfoComparison' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<InfoComparison[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  userId: undefined,
  deptId: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const zndbApi = ref<ApiTypeInfo>({})

/** 查询列表 */
const getZndbApi = async () => {
  zndbApi.value = await ApiTypeInfoApi.getApiByCode("ZCI040")
}

/** 查询列表 */
const copyContentMethod = async () => {
  navigator.clipboard.writeText(copyContent.value)
  message.success('复制成功')
}

let copyContent = ref('配偶姓名电话：张三 17600000000\n' +
  '父亲姓名电话：李四 17600000000\n' +
  '母亲姓名电话：王五 17600000000\n' +
  '朋友姓名电话：赵六 17600000000\n' +
  '同事姓名电话：赵六 17600000000');
const getZnbdText = async () => {
  copyContent.value = (await BizConfigApi.getBizConfig(5)).value
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InfoComparisonApi.getInfoComparisonPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InfoComparisonApi.deleteInfoComparison(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除智能比对 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await InfoComparisonApi.deleteInfoComparisonList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: InfoComparison[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InfoComparisonApi.exportInfoComparison(queryParams)
    download.excel(data, '智能比对.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


const formData = ref({
  content: undefined,
})
const formRules = reactive({
  content: [{ required: true, message: '客户信息不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const formSubResult = ref([]);

let leftSpan = ref(24)
let rightSpan = ref(0)

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
let submitFormDisabled = ref(false)
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  try {
    submitFormDisabled.value = true
    formSubResult.value = await InfoComparisonApi.createInfoComparison(formData.value)
    leftSpan.value = 12
    rightSpan.value = 12
    message.success(t('common.success'))
    // 发送操作成功的事件
    emit('success')
  } finally {
    getList()
    submitFormDisabled.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    deptId: undefined,
    name: undefined,
    mobile: undefined,
    result: undefined,
    queryTime: undefined,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  resetForm()
  getList()
  getZndbApi()
  getZnbdText()
})
</script>

<style scoped>
.no-border>>>.el-textarea__inner {
  border: 0; /* 去掉边框 */
  outline: none; /* 去掉聚焦时的外边框 */
  resize: none;
}
</style>
